import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import productidentification.IProductIdentifier;

public class UPCDatabaseProductIdentifier implements IProductIdentifier
{
  // this method is strictly for testing purposes.
  public static void main(String[] args)
  {
    try
    {
      String barcode = "895035002019";

      GoogleProductIdentifier identifier = new GoogleProductIdentifier();
      String result = identifier.identifyProduct(barcode);
      System.out.println("Identifying product \"" + barcode + "\" yielded: '" + result + "'");
    }
    catch (Exception e)
    {
      System.err.print("Identifying product failed! Error: ");
      if (e.getMessage() != null)
        System.err.println(e.getMessage());
      e.printStackTrace();
    }
  }

  @Override
  public String identifyProduct(String barcode) throws Exception
  {
    String uri = "http://api.upcdatabase.org/xml/f56827b394aeb36608d617961d4425f4/" + barcode;

    URL url = new URL(uri);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", "application/xml");

    InputStream xml = connection.getInputStream();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(xml);

    return doc.getElementsByTagName("description").item(0).getTextContent().trim();
  }

  @Override
  public String getName()
  {
    return "UPC Database Product Identifier Plugin";
  }

  @Override
  public String getDescription()
  {
    return "Uses upcdatabase.org to identify products based on their barcode.";
  }
}
